<template>
  <div class="tree-box">
    <div class="tit">
      <div class="name">校准列表</div>
      <span class="set force-svg-16 svgWHSet" v-html="ajustSet" @click="configVisible = true"></span>
      <template v-if="isAdjustItem">
        <div v-if="status === 2" class="btns stop-btns" title="结束校准" @click="handleStop">
          <span v-html="stopIcon"></span>
        </div>
        <div v-else class="btns" title="开始校准" @click="handleStart">
          <span v-html="playIcon"></span>
        </div>
      </template>
    </div>
    <el-scrollbar ref="treeScroll" v-loading="loadTree" style="height: calc(100% - 53px)">
      <el-tree ref="treeRef" :data="treeData" :highlight-current="true" :props="{ label: 'name' }" node-key="id"
        :expand-on-click-node="false" default-expand-all icon-class="el-icon-arrow-right" :current-node-key="current.id"
        @node-click="handleNodeClick">
        <template #default="{ data }">
          <div class="custom-tree-node">
            <span v-if="data.children" v-html="folderIcon"></span>
            <span v-else v-html="fileIcon"></span>
            <i-ep-loading v-if="data.loading" class="el-icon-loading"></i-ep-loading>
            <TooltipBox :content="data.name" :tooltipAttrs="{ placement: 'right', offset: 38 }" />
            <span v-if="current.id === data.id && status === 2 && isAdjustItem" class="adjust-icon" v-html="adjustIcon"
              :size="16"></span>
            <template v-else>
              <el-dropdown v-if="!data.children" class="dropdown-box" trigger="hover" placement="bottom-start"
                popper-class="dropdown-poper">
                <div class="more-v">
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </div>
                <template #dropdown>
                  <el-dropdown-menu slot="dropdown" class="handle-dropdown">
                    <el-dropdown-item class="edit" @click.native="openAddDialog(data)">
                      <el-icon>
                        <Edit />
                      </el-icon>
                      编辑
                    </el-dropdown-item>
                    <el-dropdown-item class="del" @click.native="handleDel(data)">
                      <span v-html="adjustDelete"></span>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
              <el-icon v-else-if="data.children.some((it: TreeItem) => !it.children)" class="add"
                @click="openAddDialog(data)">
                <CirclePlus />
              </el-icon>
            </template>
          </div>
        </template>
      </el-tree>
    </el-scrollbar>
    <AddDialog v-model="visible" :detail="chooseItem" :apiConfig="apiMap[currentKey]" :currentKey="currentKey"
      @update="getTreeList(currentKey)" />
    <InstrumneForm v-model="configVisible"></InstrumneForm>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import AddDialog from "./components/AddDialog.vue";
import InstrumneForm from "./components/InstrumneForm.vue";
import { ElTree, ElMessage, ElMessageBox } from "element-plus";
import { startAdjust, stopAdjust } from "../../../api/adjust/index";
import type { TreeItem } from "../../../api/adjust/index.d";
import { computed } from "vue";
import { apiMap, type TypeKeys } from "../../index";
import { MoreFilled, CirclePlus, Edit } from '@element-plus/icons-vue';

import { TooltipBox } from "../../../common/index.js";
import "../../../common/style.css";

import ajustSet from "../../../assets/svg/adjust/set.svg?raw";
import stopIcon from "../../../assets/svg/test/stop.svg?raw";
import playIcon from "../../../assets/svg/test/play.svg?raw";
import folderIcon from "../../../assets/svg/task/folder.svg?raw";
import fileIcon from "../../../assets/svg/task/node.svg?raw";
import adjustIcon from "../../../assets/svg/adjust/icon.svg?raw";
import adjustDelete from "../../../assets/svg/adjust/delete.svg?raw";

defineOptions({
  name: "LeftTree"
});
const authStore = {
  calibrationName: "开场校准管理器"
};
withDefaults(defineProps<{ currentKey: TypeKeys }>(), {
  currentKey: "freqscope"
});
const status = defineModel("status", { default: 1 });
const current = defineModel<Partial<TreeItem>>("current", { default: () => ({}) }); // 当前选中
const chooseItem = computed(() => current.value); // 当前选中，传给子组件
const isAdjustItem = computed(() => !current.value.children && ["lineinfo", "positioninfo"].includes(String(current.value.pId))); // 是否是校准项

const treeRef = ref<InstanceType<typeof ElTree>>();
const loadTree = ref(false);
const treeData = ref<TreeItem[]>([
  { id: "freqscope", name: "频段列表", children: [] },
  { id: "antennafactor", name: "天线因子", children: [] },
  {
    id: "lineinfo",
    name: "链路校准",
    children: [
      { id: "Reference", name: "参考校准", children: [], pId: "lineinfo" },
      { id: "Cable", name: "线缆校准", children: [], pId: "lineinfo" }
    ]
  },
  { id: "positioninfo", name: "位置校准", children: [] }
]);
const btnLoading = ref(false);
const visible = ref(false);
const configVisible = ref(false);
onMounted(() => {
  current.value = treeData.value.length ? treeData.value[0] : {};
  treeRef.value?.setCurrentKey(current.value.id);
  Object.keys(apiMap).forEach((key) => {
    getTreeList(key as TypeKeys);
  });
});
/**
 * @description: 点击节点
 * @param {*} row
 * @return {*}
 */
const handleNodeClick = (row: TreeItem) => {
  if (row.id === current.value.id) return;
  if (status.value === 2) {
    ElMessage.warning("处于校准中，请等待校准结束后查看");
    treeRef.value?.setCurrentKey(current.value.id);
    return;
  }
  current.value = row;
};

/**
 * @description: 获取列表
 * @return {*}
 */
const getTreeList = async (key: TypeKeys) => {

  console.log("key", key);

  const row = treeData.value.find((item) => item.id === key);
  if (!row) return;
  handleList(row, key);
};
const handleList = async (row: TreeItem, key: TypeKeys) => {
  if (row.id === "lineinfo") {
    row.children?.forEach((it) => {
      handleList(it, key);
    });
  } else {
    row && (row.loading = true);
    const { list, getListApi } = apiMap[key];
    const apiMethod = getListApi ? getListApi(row.id) : list;
    const { data } = await apiMethod({}, { calibrationName: authStore.calibrationName });

    row.children = ((data === "[]" ? JSON.parse(data) : data || []) as TreeItem[]).map((item) => {
      item.pId = key;
      item.pName = row.name;
      return item;
    });
    // 如果有选中，替换原来的数据
    const chooseRow = row.children.find((item) => item.id === current.value.id);
    chooseRow && (current.value = chooseRow);
    row.loading = false;
  }
};

/**
 * @description: 删除列表
 * @param {*} row
 * @return {*}
 */
const handleDel = async ({ id, pId, name }: TreeItem) => {
  const { remove, removeKey } = apiMap[pId!!];
  await ElMessageBox({
    title: "提示",
    message: `是否确定删除“${name}”?`,
    type: "warning",
    showCancelButton: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = `执行中...`;
          await remove({ [removeKey]: id } as { freqScopeId: string } & { anttennaFactorId: string } & { lineId: string } & { postionCalId: string }, {
            calibrationName: authStore.calibrationName
          });
          done();
        } catch {
          instance.confirmButtonText = `确定`;
        }
        instance.confirmButtonLoading = false;
      } else {
        done();
      }
    }
  });
  ElMessage.closeAll();
  ElMessage.success(`删除成功`);
  getTreeList(pId!!);
};

/**
 * @description: 开始校准
 * @return {*}
 */
const handleStart = async () => {
  try {
    btnLoading.value = true;
    const { id, pId } = current.value;
    await startAdjust(
      { calibrationType: pId === "lineinfo" ? "Line" : "Position", calirbationId: String(id || "") },
      { calibrationName: authStore.calibrationName }
    );
    status.value = 2;
    btnLoading.value = false;
  } catch (err: any) {
    console.log('err', err);
    btnLoading.value = false;
  }
};

/**
 * @description: 结束校准
 * @return {*}
 */
const handleStop = async () => {
  try {
    btnLoading.value = true;
    await stopAdjust({}, { calibrationName: authStore.calibrationName });
    status.value = 1;
    btnLoading.value = false;
  } catch (err) {
    btnLoading.value = false;
  }
};
/**
 * @description: 打开新增、编辑弹窗
 * @param {*} row
 * @return {*}
 */
const openAddDialog = (row: TreeItem) => {
  current.value = row;
  visible.value = true;
};
defineExpose({ handleStop });
</script>

<style lang="scss" scoped>
.tree-box {
  height: 100%;

  .tit {
    height: 52px;
    padding: 0 16px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #eaeaea;

    .name {
      font-weight: bold;
      font-size: 14px;
    }

    .set {
      margin: 0 0 0 auto;
      cursor: pointer;
      color: #008efa;
    }

    .svgWHSet {
      display: inline-block;
      width: 16px !important;
      height: 16px !important;
    }

    .force-svg-16 :deep(svg) {
      width: 16px !important;
      height: 16px !important;
    }

    .force-svg-16 :deep(svg *),
    .force-svg-16 :deep(svg) {
      width: 16px !important;
      height: 16px !important;
    }

    .btns {
      width: 26px;
      height: 26px;
      border-radius: 2px;
      background-color: #dddddd;
      margin-left: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;

      &.stop-btns {
        color: #fd3b3b;

        &:hover {
          color: #fd3b3b;
        }
      }

      &:hover {
        background-color: #ccc;
        color: #008efa;
        transition: all 0.3s;

        :deep(.svg-icon) {
          transform: scale(1.2);
        }
      }

      :deep(.svg-icon) {
        width: 10px;
        height: 10px;
      }
    }
  }

  :deep(.el-scrollbar) {
    .el-tree {
      &.el-tree--highlight-current {
        .el-tree-node {
          &>.el-tree-node__content {
            &:hover {
              background: #e4e6f1;
              color: #333;
            }
          }

          &.is-current {
            &>.el-tree-node__content {
              background: #e4e6f1;
              color: #008efa;
            }
          }
        }
      }

      .el-tree-node {
        .el-tree-node__content {
          height: 32px;

          &:hover {
            .custom-tree-node {
              .dropdown-box {
                .more-v {
                  display: block;
                }
              }

              .add {
                display: block;
              }
            }
          }

          .custom-tree-node {
            width: calc(100% - 54px);
            display: flex;
            align-items: center;
            justify-content: space-between;

            .svg-icon {
              margin-right: 5px;
            }

            .el-icon-loading {
              animation: rotating 2s linear infinite;
            }

            .name {
              margin-right: auto;
            }

            .dropdown-box {
              .more-v {
                outline: none;
                display: none;
              }
            }

            .add {
              font-size: 13px;
              display: none;
              min-width: 16px;

              &:hover {
                color: #008efa;
              }
            }

            .adjust-icon {
              margin: 0 0 0 5px;
            }
          }
        }
      }

      .el-tree-node__expand-icon {
        color: #666;
        font-weight: bold;
        margin-left: 10px;

        &.is-leaf {
          color: transparent;
          opacity: 0;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.dropdown-poper {
  .el-dropdown-menu {
    &.handle-dropdown {
      box-sizing: border-box;
      padding: 5px 0;

      .el-dropdown-menu__item {
        padding: 0 13px;
        height: 24px;
        line-height: 24px;
        font-size: 12px;

        &.edit {
          color: #008efa;
        }

        &.del {
          color: #fd3b3b;
        }

        .svg-icon {
          width: 12px;
          height: 12px;
          margin-right: 4px;
        }
      }
    }
  }

  .el-popper__arrow {
    display: none !important;
  }
}
</style>
